package com.example.springcloudzuul.web;

import com.example.springcloudzuul.util.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;

import java.util.Enumeration;

@Component
public class AuthFilter  extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String path = context.getRequest().getServletPath();
        if("/order/order".equals(path) ||
                "/spring-cloud-order/order".equals(path) ){
            return true;
        }

        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext rc = RequestContext.getCurrentContext();
        Enumeration<String> headerNames = rc.getRequest().getHeaderNames();
        while(headerNames.hasMoreElements()){
            String name = headerNames.nextElement();
            System.out.println(name + " = " + rc.getRequest().getHeader(name));
        }
        //获取令牌
        String jwt = rc.getRequest().getHeader("Authorization");
        // axios.get('xxxx',{ headers:{Authorization:jwt}})
        // 思考: 超链接请求, 怎么获取 jwt: cookie + 请求参数

        System.out.println("jwt = " + jwt);
        //验证jwt
        if(jwt == null){
            response("用户认证失败！");

            return null;
        }

        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            System.out.println("claims = " + claims);
            Object myname = claims.get("myname");
            System.out.println("myname = " + myname);
            rc.addZuulRequestHeader("myname", myname.toString());

        }
        catch (Exception e){
            response("用户jwt格式错误！");
        }
        


        return null;
    }

    private void response(String s) {
        RequestContext rc = RequestContext.getCurrentContext();
        //阻止请求访问 目标资源
        rc.setSendZuulResponse(false);
        rc.setResponseBody(s);

    }
}
